import urllib,urllib2,re,xbmcplugin,xbmcgui,os

###################################################################################
##
##      PIRATEBAY
##      -------------------------------------
##      0.1  - First version with only basic Navigation
###################################################################################
##      Todo:
##      - Error Checking
##      - Extended Labels Info
##      - Text Search
##      - TV Show Search
###################################################################################

MyPath  = os.getcwd()
MyMedia = MyPath +'\\media'
BURL    = 'http://thepiratebay.org'

## Variable Set Refresh or No Refresh
DirRefresh = False

def UpdateSettings():
        print '--UpdateSettings--'
        global SORTORDER,FILTERSEEDS
        tmp            =   {'0':'1','1':'4','2':'5','3':'7','4':'9'}
        SORTORDER      =   tmp[xbmcplugin.getSetting("sortorder")]
        FILTERSEEDS    =   xbmcplugin.getSetting("filterseeds")
        print 'Sortorder:' + str(SORTORDER) +' -- Filter Seeds:'+ str(FILTERSEEDS)


def Comms(url):
        print '--Comms--'
        ## Standard code
        req = urllib2.Request(url)
        req.add_header('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3')
        response = urllib2.urlopen(req)
        link=response.read()
        response.close()
        return link

        
def CATS(url):
        print '--CATS--'
        ## Get html data
        ## <dt><a href="/browse/100" title="Audio">Audio</a></dt>
        link = Comms(url)

        Exp = re.compile('<a href=\"(/browse/.*?)\" title=\"(.*?)\">(.*?)</a>')
        Tar = re.findall(Exp,link)

        SubCat = ''
        for _a in Tar:
                if _a[0].endswith('00'):
                        SubCat = str(_a[2])
                        addDir(SubCat +' - All','',BURL + str(_a[0]) +'/0/'+ SORTORDER,1, MyMedia +'\\folder.png')
                addDir(SubCat +' - '+ str(_a[2]),'',BURL + str(_a[0]) +'/0/'+ SORTORDER,1, MyMedia +'\\folder.png')
        

def AddPages(link,url):
        #&nbsp;<a href="/browse/200/1/3"><img src="http://static.thepiratebay.org/img/next.gif" border="0" alt="Next"/>
        Pex   = re.compile('<a href=\"(/browse/[0-9]+?/[0-9]+?/[0-9]+?)\">')
        Pages = re.findall(Pex,link)
        if len(Pages) > 0:
                print Pages[-1]
                addDir('>>>> NEXT PAGE >>>>',url,BURL + str(Pages[-1]),1, MyMedia +'\\folder.png')
                
        
        
def FILES(url):
        print '--FILES--'
        ## Get html data
        link = Comms(url)

        AddPages(link,url)

        Exp = re.compile('<a href=\"/torrent/.*?>(.*?)<.*?'             ## Torrent name
                         '<td>(.*?)</td>.*?'                            ## Date
                         '<td><a href=\"(.*?)\".*?>.*?</td>.*?'         ## Torrent Url
                         '<td align=\"right\">(.*?)</td>.*?'            ## Size
                         '<td align=\"right\">(.*?)</td>.*?'            ## Seeds
                         '<td align=\"right\">(.*?)</td>.*?'            ## Leeches
                         '</tr>',re.DOTALL)

        Tar = re.findall(Exp,link)
        Tor     =   {}

        for _a in Tar :
                Nm                  =   str(_a[0])
                Tor[Nm]             =   {}
                Tor[Nm]['Date']     =   re.sub('<.*?>','',str(_a[1]).replace('&nbsp;',' '))
                Tor[Nm]['Url']      =   str(_a[2])
                Tor[Nm]['Size']     =   str(_a[3]).replace('&nbsp;',' ')
                Tor[Nm]['Seeds']    =   str(_a[4]) +'('+ str(_a[5]) +')'
                if  ( _a[4].isdigit() )  : 
                    if   int(_a[4])    ==   0                                   :   Health = 5
                    elif int(_a[4])    >    0   and     int(_a[4])     <=  10   :   Health = 3
                    elif int(_a[4])    >    10  and     int(_a[4])     <=  50   :   Health = 2
                    elif int(_a[4])    >    50                                  :   Health = 4
                    else                                                        :   Health = 1
                else                                                            :   Health = 1
                Tor[Nm]['Health']   =   str(Health)

                Image  =   MyMedia +'\\Health-'+ str(Health) +'.png'
                Label1 = str(Nm) + ' [ Size: '+ str(Tor[Nm]['Size']) +' ] [ Seeds: '+ str(Tor[Nm]['Seeds']) +' ]'
                if FILTERSEEDS == 'true' and Health != 5:
                        addDir(Label1,url,Tor[Nm]['Url'],2, Image)

        AddPages(link,url)

        
def SaveFiles(name,url)  :
        ## Create static directory locations.
        RootPath = "special://profile/torrents/"
        
        if not os.path.exists(RootPath):
                os.mkdir(RootPath)

        NewName = NiceName(name)
        FullPath = RootPath + NewName

        ## Get html data
        link = Comms(url)
                
        ## Save The file
        f   =   open(str(FullPath),'wb')
        f.write(link)
        f.close()
                

def NiceName(fName):
        NewName     =   ''
        tName       =   fName.rsplit('.',1)
        xName       =   tName[0][:30]
        if ( xName[0].isdigit() )   :
                xName = 'x'+ str(xName)
        for xChar in xName                  :
                if      xChar.isalnum()         :   NewName  += str(xChar)
                elif    xChar.isspace()         :   NewName  += '_'
                else                            :   pass
        if len(NewName) > 4                 :
                return NewName +'.torrent'
        else                                :
                return None



def get_params():
        param=[]
        paramstring=sys.argv[2]
        if len(paramstring)>=2:
                params=sys.argv[2]
                cleanedparams=params.replace('?','')
                if (params[len(params)-1]=='/'):
                        params=params[0:len(params)-2]
                pairsofparams=cleanedparams.split('&')
                param={}
                for i in range(len(pairsofparams)):
                        splitparams={}
                        splitparams=pairsofparams[i].split('=')
                        if (len(splitparams))==2:
                                param[splitparams[0]]=splitparams[1]
                                
        return param



def addDir(name,label, url,mode,iconimage):
        u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)+"&label="+urllib.quote_plus(label)
        ok=True
        liz=xbmcgui.ListItem(name, label, iconImage="DefaultFolder.png", thumbnailImage=iconimage)
        liz.setInfo( type="Video", infoLabels={ "Title": name } )
        ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=True)
        return ok
        
UpdateSettings()

params=get_params()
url=None
name=None
mode=None
label=None

try:
        url=urllib.unquote_plus(params["url"])
except:
        pass
try:
        name=urllib.unquote_plus(params["name"])
except:
        pass
try:
        mode=int(params["mode"])
except:
        pass
try:
        name=urllib.unquote_plus(params["label"])
except:
        pass

print "Mode: "+str(mode)
print "URL: "+str(url)
print "Name: "+str(name)
print "Label: "+str(label)

if mode==None or url==None or len(url)<1:
        CATS(BURL +'/browse')
       
if mode==1:
        print '-- Files --'
        FILES(url)
        
if mode==2:
        print '-- Save --'
        SaveFiles(urllib.unquote_plus(params["name"]),urllib.unquote_plus(params["url"]))
        FILES(urllib.unquote_plus(params["label"]))
        DirRefresh = True

xbmcplugin.addSortMethod(int(sys.argv[1]), 0)
xbmcplugin.endOfDirectory(int(sys.argv[1]),updateListing=DirRefresh)

